package com.syni.mdd.yhd.common.all.service.pay.aiPay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.syni.mdd.yhd.common.all.utils.RestTemplateUtils;
import com.syni.mdd.yhd.common.all.utils.WebUtils;
import com.syni.mdd.sjb.common.component.utils.common.spring.ApplicationContextHolder;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.yhd.common.all.config.pay.alipay.AlipayConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.aliPay.AliPayController;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.record.ReOrderLog;
import com.syni.mdd.yhd.common.all.entity.record.ReOrderRefundLog;
import com.syni.mdd.yhd.common.all.entity.record.ReTransferLog;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.listen.order.OrderEvent;
import com.syni.mdd.yhd.common.all.listen.order.OrderRefundCompleteListener;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.record.ReOrderRefundLogService;
import com.syni.mdd.yhd.common.all.service.record.ReTransferLogService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.vo.rp.user.AuthMiniAppUserVo;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.syni.mdd.yhd.common.all.utils.AliPayUtil.getRequestNo;

@Service
public class AlipayServiceImpl implements AliPayService {

    @Autowired
    @Qualifier("oldAliPayConfig")
    AlipayConfig oldAliPayConfig;

    @Autowired
    @Qualifier("aliPayConfig")
    AlipayConfig alipayConfig;

    @Autowired
    @Qualifier("aliMiniAppConfig")
    AlipayConfig aliMiniAppConfig;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsBusinessinfoService bmsBusinessinfoService;

    @Autowired
    AliPayController aliPayController;

    @Autowired
    ReOrderLogService reOrderLogService;

    @Autowired
    BmsFullCouponService bmsFullCouponService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    ReTransferLogService reTransferLogService;

    @Autowired
    BmsLocalLifeService bmsLocalLifeService;

    @Autowired
    ReOrderRefundLogService reOrderRefundLogService;

    private AlipayClient aliMiniAppClient = null;

    public final static Map<Integer,String> PAY_TITLE_MAP = new HashMap<>();

    static {
        PAY_TITLE_MAP.put(Constants.ONLINE_ORDER_TYPE,"%s -【线上买单】");
        PAY_TITLE_MAP.put(Constants.COUPONS_ORDER_TYPE,"%s -【(%s折)买单】");
        PAY_TITLE_MAP.put(Constants.GROUP_BUY_ORDER_TYPE,"%s -【%s】");
        PAY_TITLE_MAP.put(Constants.FX_ORDER_TYPE,"%s -【%s】");
        PAY_TITLE_MAP.put(Constants.GROUP_BUY_BARGAIN_ORDER_TYPE,"%s -【%s】");

    }

    public final static String PAY_DEFAULT_TITLE = "订单支付";
    public final static String PAY_DEFAULT_DESC = "默认描述";
    private Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);


    @Override
    public Map<String, Object> appOrderQuery(String orderNo,Double actualConsum) {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isPay",Constants.COMMON_FLAG_FALSE_INT);
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
        alipayTradeQueryModel.setOutTradeNo(orderNo);
        request.setBizModel(alipayTradeQueryModel);
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error("appOrderQuery error",e);
        }
        if(response.isSuccess()){
            log.info("orderQuery data : " + JSON.toJSONString(response));
            String tradeStatus =  response.getTradeStatus();
            String totalAmount = response.getTotalAmount();
            if(tradeStatus.equals("TRADE_SUCCESS") && totalAmount.equals(ArithUtil.turnDecimal(actualConsum,2).toString())){
                resultMap.put("isPay",Constants.COMMON_FLAG_TRUE_INT);
                resultMap.put("date",response.getSendPayDate());
                resultMap.put("tradeNo",response.getTradeNo());
            }
        }
        return resultMap;
    }

    public Map<String, Object> appOrderQuery(String orderNo,AlipayClient alipayClient) {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isPay",Constants.COMMON_FLAG_FALSE_INT);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
        alipayTradeQueryModel.setOutTradeNo(orderNo);
        request.setBizModel(alipayTradeQueryModel);
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error("appOrderQuery error",e);
        }
        if(response.isSuccess()){
            log.info("orderQuery data : " + JSON.toJSONString(response));
            String tradeStatus =  response.getTradeStatus();
            if(tradeStatus.equals("TRADE_SUCCESS")){
                resultMap.put("isPay",Constants.COMMON_FLAG_TRUE_INT);
                resultMap.put("date",response.getSendPayDate());
                resultMap.put("tradeNo",response.getTradeNo());
                resultMap.put("totalAmount",response.getTotalAmount());
            }
        }
        return resultMap;
    }

    public void appAliPayNotify(HttpServletRequest request, String alipay_public_key) {
        System.out.println("----------------阿里服务器消费手机回调-------" + request);
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        log.info("回调数据：" + JSON.toJSONString(params));
        Date nowTime = new Date();
        //ReOrderLog orderLog = new ReOrderLog();
        //orderLog.setNewTime(nowTime);
        try {
            // 调用SDK验证签名
            boolean flag = AlipaySignature.rsaCheckV1(params, alipay_public_key,"UTF-8", "RSA2");
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            String info = "flag==" + flag + ";out_trade_no = " + out_trade_no + ";trade_no" + trade_no
                    + ";trade_status = " + trade_status + ";total_amount=" + total_amount;
            log.info(info);
            if (flag && trade_status.equals("TRADE_SUCCESS")) {
                //TODO
                // 修改订单状态
                // 已缴费----开始处理业务
                //orderLog.setCallBackIsSuccess(Constants.COMMON_FLAG_TRUE_INT);
                log.info(out_trade_no +" 用户已付款：.................................." );
                BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByOrderNo(out_trade_no);
                bmsDxOrder.setPayNo(trade_no);
                bmsDxOrder.setPayWay(Constants.ALI_PAY);
                bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                if(orderPayHand(info,bmsDxOrder,nowTime)){
                    bmsDxOrder.setPayTime(nowTime);
                    bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("Ali pay callBack FAIL",e);
        }
    }

    public void test(Integer orderId,Integer payWay) {
        Date nowTime = new Date();
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findById(orderId).get();
        bmsDxOrder.setPayNo(String.format("test_%s",String.valueOf(System.currentTimeMillis())));
        bmsDxOrder.setPayTime(nowTime);
        if(payWay != null){
            bmsDxOrder.setPayWay(Constants.WX_PAY);
        }
        if(orderPayHand("test",bmsDxOrder,nowTime)){
            bmsDxOrderService.getBaseDao().save(bmsDxOrder);
        }
    }


    public boolean orderPayHand(String info,BmsDxOrder bmsDxOrder,Date nowTime){
        //加锁拦截下
        String lockValue = WebUtils.getUUId();
        String lockKey = Constants.REDIS_ORDER_HANDLER + bmsDxOrder.getOrderNo();
        boolean lockResult = RedisTemplateUtils.addLockCanWait(lockKey,lockValue,3600 * 3600);
        if(!lockResult){
            return false;
        }
        boolean HAND_ORDER = false;
        //订单记录
        ReOrderLog orderLog = new ReOrderLog();
        orderLog.setNewTime(nowTime);
        orderLog.setInfo(info);
        orderLog.setCallBackIsSuccess(Constants.COMMON_FLAG_TRUE_INT);
        try {
            if(bmsDxOrder != null){
                orderLog.setOrderId(bmsDxOrder.getId());
                //修改订单状态
                BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(bmsDxOrder.getId(), Constants.NO_PAY);
                if(bmsDxOrderStatus != null) {
                    HAND_ORDER = true;
                    orderLog.setOrderStatus(Constants.COMMON_FLAG_TRUE_INT);
                    orderLog.setOrderType(bmsDxOrderStatus.getOrderType());
                    if (bmsDxOrderStatus.getOrderType() == Constants.ONLINE_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.COUPONS_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                        bmsDxOrderStatus.setPayTime(nowTime);
                        //转钱进入商家支付宝,对商家进行分账
                        //进行分账（尝试5次调用）
                        final int TRY_AGRING = 5;
                        List<BmsBusinessInfo> bmsBusinessinfos = bmsBusinessinfoService.getBaseDao().findByBusinessIdAndAlipayStatus(bmsDxOrderStatus.getBusinessId(),Constants.COMMON_FLAG_TRUE_INT);
                        if(bmsBusinessinfos != null && bmsBusinessinfos.size() > 0){
                            BmsBusinessInfo bmsBusinessInfo = bmsBusinessinfos.get(0);
                            Double settleMoney = bmsDxOrder.getSettleMoney();
                            if(settleMoney > 0d) {
                                //进行分账
                                int count = 0;
                                while (count < TRY_AGRING) {
                                    count++;
                                    Map<String, Object> resultMap = aliPayController.settleForService(bmsDxOrder.getPayNo(),
                                            bmsBusinessInfo.getAlipayUid(), settleMoney.toString());
                                    orderLog.setSettleData(resultMap.get("settleData").toString());
                                    if (resultMap.containsKey("status") &&
                                            ResultCode.CODE_NORMAL.equals(resultMap.get("status").toString())) {
                                        orderLog.setSettleIsSuccess(Constants.COMMON_FLAG_TRUE_INT);
                                        break;
                                    }
                                }
                            }
                            //if(bmsDxOrder.getFullCouponId() != null){
                            //进行转账
                            Double shopConsum = bmsDxOrder.getShopConsum();
                            Double transfer = shopConsum;
                            if(settleMoney > 0d) {
                                transfer = ArithUtil.sub(shopConsum, settleMoney);
                            }
                            if(bmsDxOrder.getPayNo() != null) {
                                if (bmsDxOrder.getPayNo().startsWith("test")) {
                                    transfer = 0d;
                                }
                            }
                            if(transfer > 0d) {
                                ReTransferLog reTransferLog = new ReTransferLog();
                                int count = 0;
                                while (count < TRY_AGRING) {
                                    count++;
                                    Map<String, Object> transMap = aliPayController.transferFullCoupon(bmsDxOrder, bmsBusinessInfo.getAlipayUid(), transfer.toString(), reTransferLog);
                                    orderLog.setTranferLog(JSON.toJSONString(transMap));
                                    if(transMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(transMap.get("status").toString())){
                                        break;
                                    }
                                }
                                reTransferLogService.getBaseDao().save(reTransferLog);
                            }
                            //}
                        }
                    } else if (bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.FX_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.ALREADY_USE);
                        if(bmsDxOrder.getBmsDxGroupBuy() != null){
                            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                            if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                                bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                            }
                        }
                    }else if (bmsDxOrderStatus.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE) {
                        Integer isChangePrice = bmsDxOrder.getIsChangePrice();
                        if(isChangePrice == 1){
                            bmsDxOrderStatus.setStatus(Constants.WAIT_GET);
                            //bmsDxOrderService.transMoneyToCoustomer(bmsDxOrder);
                        }else{
                            bmsDxOrderStatus.setStatus(Constants.NO_PAY);
                        }
                        //本地生活产品销量+1
                        pushAddLifeSale(bmsDxOrder.getLifeId());
                    }else if (bmsDxOrderStatus.getOrderType() == Constants.PLATFORM_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                    }
                    //普通团购、秒杀团购和砍价团购 如果商家端核销设置为否,则状态为已完成
                    if(bmsDxOrder.getBmsDxGroupBuy() != null){
                        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                        if(bmsDxGroupBuy.getGroupType() != null && (bmsDxGroupBuy.getIsBusinessConsume() != null
                                && bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_FALSE_INT)
                                && (bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_GEN ||
                                bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_BARGAIN ||
                                bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_MS)){
                            bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                            //todo:分销逻辑
                        }
                    }
                    bmsDxOrderStatus.setPayTime(nowTime);
                    bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
                    log.info("订单id：" + bmsDxOrder.getId() + "............支付完成");
                    //如果是团购订单，生成对应的团购券
                    if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                            || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE || bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
                        //插入团购券表记录
                        orderLog = bmsDxGroupBuyUseService.generateGroupUse(orderLog,bmsDxOrder,nowTime);
                    }

                    //添加一个订单消费监听
                    BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderPay",bmsDxOrder));
                }
            }
        }catch (Exception e){
            orderLog.setPayError(e.toString());
        }finally {
            reOrderLogService.getBaseDao().save(orderLog);
            RedisTemplateUtils.releaseLock(lockKey,lockValue);
        }
        return HAND_ORDER;
    }

    public boolean orderPayHand_V2(String info,BmsDxOrder bmsDxOrder,Date nowTime){
        boolean HAND_ORDER = false;
            if(bmsDxOrder != null){
                //修改订单状态
                BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(bmsDxOrder.getId(), Constants.NO_PAY);
                if(bmsDxOrderStatus != null) {
                    HAND_ORDER = true;
                    if (bmsDxOrderStatus.getOrderType() == Constants.ONLINE_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.COUPONS_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                        bmsDxOrderStatus.setPayTime(nowTime);
                        //转钱进入商家支付宝,对商家进行分账
                        //进行分账（尝试5次调用）
                        final int TRY_AGRING = 5;
                        List<BmsBusinessInfo> bmsBusinessinfos = bmsBusinessinfoService.getBaseDao().findByBusinessIdAndAlipayStatus(bmsDxOrderStatus.getBusinessId(),Constants.COMMON_FLAG_TRUE_INT);
                        if(bmsBusinessinfos != null && bmsBusinessinfos.size() > 0){
                            BmsBusinessInfo bmsBusinessInfo = bmsBusinessinfos.get(0);
                            Double settleMoney = bmsDxOrder.getSettleMoney();
                            if(settleMoney > 0d) {
                                //进行分账
                                int count = 0;
                                while (count < TRY_AGRING) {
                                    count++;
                                    Map<String, Object> resultMap = aliPayController.settleForService(bmsDxOrder.getPayNo(),
                                            bmsBusinessInfo.getAlipayUid(), settleMoney.toString());
                                    if (resultMap.containsKey("status") &&
                                            ResultCode.CODE_NORMAL.equals(resultMap.get("status").toString())) {
                                        break;
                                    }
                                }
                            }
                            //if(bmsDxOrder.getFullCouponId() != null){
                            //进行转账
                            Double shopConsum = bmsDxOrder.getShopConsum();
                            Double transfer = shopConsum;
                            if(settleMoney > 0d) {
                                transfer = ArithUtil.sub(shopConsum, settleMoney);
                            }
                            if(bmsDxOrder.getPayNo() != null) {
                                if (bmsDxOrder.getPayNo().startsWith("test")) {
                                    transfer = 0d;
                                }
                            }
                            if(transfer > 0d) {
                                ReTransferLog reTransferLog = new ReTransferLog();
                                int count = 0;
                                while (count < TRY_AGRING) {
                                    count++;
                                    Map<String, Object> transMap = aliPayController.transferFullCoupon(bmsDxOrder, bmsBusinessInfo.getAlipayUid(), transfer.toString(), reTransferLog);
                                    if(transMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(transMap.get("status").toString())){
                                        break;
                                    }
                                }
                                reTransferLogService.getBaseDao().save(reTransferLog);
                            }
                            //}
                        }
                    } else if (bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.FX_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.ALREADY_USE);
                        if(bmsDxOrder.getBmsDxGroupBuy() != null){
                            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                            if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                                bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                            }
                        }
                    }else if (bmsDxOrderStatus.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE) {
                        Integer isChangePrice = bmsDxOrder.getIsChangePrice();
                        if(isChangePrice == 1){
                            bmsDxOrderStatus.setStatus(Constants.WAIT_GET);
                            bmsDxOrderService.transMoneyToCoustomer(bmsDxOrder);
                        }else{
                            bmsDxOrderStatus.setStatus(Constants.NO_PAY);
                        }
                        //本地生活产品销量+1
                        pushAddLifeSale(bmsDxOrder.getLifeId());

                    }else if (bmsDxOrderStatus.getOrderType() == Constants.PLATFORM_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                    }
                    //普通团购、秒杀团购和砍价团购 如果商家端核销设置为否,则状态为已完成
                    if(bmsDxOrder.getBmsDxGroupBuy() != null){
                        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                        if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_FALSE_INT
                                && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_GEN ||
                                bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_BARGAIN ||
                                bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_MS){
                            bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                            //todo:分销逻辑
                        }
                    }
                    bmsDxOrderStatus.setPayTime(nowTime);
                    bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
                    log.info("订单id：" + bmsDxOrder.getId() + "............支付完成");
                    //如果是团购订单，生成对应的团购券
                    if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                            || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE || bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
                        //插入团购券表记录
                        bmsDxGroupBuyUseService.generateGroupUse_V2(bmsDxOrder,nowTime);
                    }

                    //添加一个订单消费监听
                    BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderPay",bmsDxOrder));
                }
            }

        return HAND_ORDER;
    }

    private void pushAddLifeSale (Integer lifeId) {
        BmsLocalLife bmsLocalLife = bmsLocalLifeService.getBaseDao().getOne(lifeId);
        if(bmsLocalLife != null){
            bmsLocalLife.setSaleNum(bmsLocalLife.getSaleNum() + 1);
            bmsLocalLifeService.getBaseDao().save(bmsLocalLife);
        }

    }


    public boolean orderPayHandTest(BmsDxOrder bmsDxOrder,Date nowTime){
        boolean HAND_ORDER = false;
        //订单记录
        ReOrderLog orderLog = new ReOrderLog();
        orderLog.setNewTime(nowTime);
        orderLog.setInfo("");
        orderLog.setCallBackIsSuccess(Constants.COMMON_FLAG_TRUE_INT);
        try {
            if(bmsDxOrder != null){
                orderLog.setOrderId(bmsDxOrder.getId());
                //修改订单状态
                BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(bmsDxOrder.getId(), Constants.NO_PAY);
                if(bmsDxOrderStatus != null) {
                    HAND_ORDER = true;
                    orderLog.setOrderStatus(Constants.COMMON_FLAG_TRUE_INT);
                    orderLog.setOrderType(bmsDxOrderStatus.getOrderType());
                    if (bmsDxOrderStatus.getOrderType() == Constants.ONLINE_ORDER_TYPE
                            || bmsDxOrderStatus.getOrderType() == Constants.COUPONS_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                    } else if (bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE) {
                        bmsDxOrderStatus.setStatus(Constants.ALREADY_USE);
                    }
                    bmsDxOrderStatus.setPayTime(nowTime);
                    bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
                    log.info("订单id：" + bmsDxOrder.getId() + "............支付完成");
                    //如果是团购订单，生成对应的团购券
                    if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                            || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                        //插入团购券表记录
                        orderLog = bmsDxGroupBuyUseService.generateGroupUse(orderLog,bmsDxOrder,nowTime);
                    }
                    //添加一个订单消费监听
                    BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderPay",bmsDxOrder));
                }
            }
        }catch (Exception e){
            orderLog.setPayError(e.toString());
        }finally {
            reOrderLogService.getBaseDao().save(orderLog);
        }
        return HAND_ORDER;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> refund(AlipayClient alipayClient, AlipayTradeRefundRequest request, ParamsMap paramsMap) throws Exception {
        Map<String,Object> handleMap = bmsDxOrderService.userRefundOrderOrder(paramsMap);
        if(!ResultCode.CODE_NORMAL.equals(handleMap.get("status").toString())){
            return handleMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) handleMap.get("data");
        Map<String,Object> userDataMap = (Map<String, Object>) handleMap.get("userData");
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_trade_no",bmsDxOrder.getOrderNo());
        b1.put("refund_amount",userDataMap.get("refundTotal"));
        b1.put("refund_reason","正常退款");
        b1.put("out_request_no", AliPayUtil.getRequestNo());
        request.setBizContent(JSON.toJSONString(b1));
        List<BmsDxGroupBuyUse> groupBuyUseList = (List<BmsDxGroupBuyUse>) userDataMap.get("bmsDxGroupBuyUses");
        //存储处理时间
        Date nowTime = new Date();
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseList){
            bmsDxGroupBuyUse.setAcceptTime(nowTime);
        }
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(bmsDxOrder.getPayNo().length() >= 28) {
            System.out.println("回调json：" + JSON.toJSONString(response));
            if (!response.isSuccess()) {
                throw new Exception("api接口调用失败");
            }
            for (BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseList) {
                bmsDxGroupBuyUse.setRefundTime(response.getGmtRefundPay());
            }
        }else {
            for (BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseList) {
                bmsDxGroupBuyUse.setRefundTime(nowTime);
            }
        }
        userDataMap.put("refundTime", DateTimeUtils.converDateToString(groupBuyUseList.get(0).getRefundTime(),DateTimeUtils.DATE_PATTERN_DAY_05));
        userDataMap.put("refundNum",groupBuyUseList.size());
        //保存状态和时间
        bmsDxGroupBuyUseService.getBaseDao().saveAll(groupBuyUseList);
        //发送消息
        BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderRefund",bmsDxOrder,userDataMap));
        return ResultMapHelper.success(userDataMap, ResultMsg.CODE_ORDER_RUFUND_SUCCESS);
    }

    public boolean refundMoney(BmsDxOrder bmsDxOrder,Double orderRefund,AlipayClient alipayClient){
        String requestNo = AliPayUtil.getRequestNo();
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_trade_no",bmsDxOrder.getOrderNo());
        b1.put("refund_amount",orderRefund.toString());
        b1.put("refund_reason","正常退款");
        b1.put("out_request_no", requestNo);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent(JSON.toJSONString(b1));
        AlipayTradeRefundResponse response = null;
        try {
            if(bmsDxOrder.getActualConsum() > 0d) {
                if (!bmsDxOrder.getPayNo().startsWith("test")) {
                    response = alipayClient.execute(request);
                    log.info("aliPay refund result：" + JSON.toJSONString(response));
                    if(!response.isSuccess()){
                        return false;
                    }
                    String fundChange = response.getFundChange();
                    if(!fundChange.equals("Y")){
                        return false;
                    }
                    //查询一下是否真的退款成功
                    //this.orderRefundQuery(bmsDxOrder.getOrderNo(),requestNo);
                    BmsCommonService.getApplicationContext().publishEvent(new OrderEvent(OrderRefundCompleteListener.MODEL_COMPLETE,bmsDxOrder,orderRefund, ReOrderRefundLog.ALI_PAY,requestNo));
                    return true;
                }
            }
        } catch (AlipayApiException e) {
            log.error("ali refund error : ",e);
            return false;
        }
        return true;
    }

    public String getOrderSubject(BmsDxOrder bmsDxOrder){
        String subject = AlipayServiceImpl.PAY_DEFAULT_TITLE;
        try {
            if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE){
                subject = String.format(AlipayServiceImpl.PAY_TITLE_MAP.get(Constants.ONLINE_ORDER_TYPE),bmsDxOrder.getVendorName());
            }else if(bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE) {
                BmsDxCoupon bmsDxCoupon = bmsDxOrder.getBmsDxCoupon();
                subject = String.format(AlipayServiceImpl.PAY_TITLE_MAP.get(Constants.COUPONS_ORDER_TYPE),bmsDxOrder.getVendorName(),bmsDxCoupon.getPayContent());
            }else if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                subject = String.format(AlipayServiceImpl.PAY_TITLE_MAP.get(Constants.GROUP_BUY_ORDER_TYPE),bmsDxOrder.getVendorName(),bmsDxGroupBuy.getGroupName());
            }else if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                subject = String.format(AlipayServiceImpl.PAY_TITLE_MAP.get(Constants.GROUP_BUY_BARGAIN_ORDER_TYPE),bmsDxOrder.getVendorName(),bmsDxGroupBuy.getGroupName());
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return subject;
    }

    @Override
    public void transfersMoneyToCustomerByAliPay(BmsDxOrder bmsDxOrder, String uid) {
        Double transMoney = bmsDxOrder.getChangePrice();
        if(transMoney > 0d && transferFullCoupon(transMoney,uid)){
            ReTransferLog reTransferLog = new ReTransferLog();
            reTransferLog.setOrderId(bmsDxOrder.getId());
            reTransferLog.setBusinessPayId(uid);
            reTransferLog.setTotal(transMoney);
            reTransferLog.setNewTime(new Date());
            reTransferLog.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            reTransferLog.setChannel(ReTransferLogService.CHANNEL_LOCAL_ORDER);
            reTransferLogService.getBaseDao().save(reTransferLog);
        }
    }

    @Override
    public boolean transfersMoneyToPersonalAlipay(Double transMoney, String uid,String bizNo) {
        if(transMoney > 0d && transferFullCoupon(transMoney,uid,bizNo)){
            ReTransferLog reTransferLog = new ReTransferLog();
            reTransferLog.setBusinessPayId(uid);
            reTransferLog.setTotal(transMoney);
            reTransferLog.setNewTime(new Date());
            reTransferLog.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            reTransferLog.setBizNo(bizNo);
            reTransferLogService.getBaseDao().save(reTransferLog);
            return true;
        }
        return false;
    }

    @Override
    public boolean transfersMoneyToPersonalAlipay(Double transMoney, String uid,String bizNo,Integer channel) {

        if(transMoney > 0d && transferFullCoupon(transMoney,uid,bizNo)){
            ReTransferLog reTransferLog = new ReTransferLog();
            reTransferLog.setBusinessPayId(uid);
            reTransferLog.setTotal(transMoney);
            reTransferLog.setNewTime(new Date());
            reTransferLog.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            reTransferLog.setBizNo(bizNo);
            reTransferLog.setChannel(channel);
            reTransferLogService.getBaseDao().save(reTransferLog);
            return true;
        }
        return false;
    }

    public boolean transferFullCoupon(Double transMoney,String businessPayId) {
        businessPayId = businessPayId.replaceAll(" ","");
        AlipayClient alipayClient = getAlipayClient();
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_biz_no",getRequestNo());
        b1.put("payee_type","ALIPAY_USERID");
        b1.put("payee_account",businessPayId);
        b1.put("amount",transMoney);
        b1.put("remark","觅东东平台转账");

        request.setBizContent(JSON.toJSONString(b1));
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        if(response.isSuccess()){
            return true;
        }
        return false;
    }

    public boolean transferFullCoupon(Double transMoney,String businessPayId,String bizNo) {
        businessPayId = businessPayId.replaceAll(" ","");
        AlipayClient alipayClient = getAlipayClient();
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        Map<String,Object> b1 = new HashMap<>();
        b1.put("out_biz_no",bizNo);
        b1.put("payee_type","ALIPAY_USERID");
        b1.put("payee_account",businessPayId);
        b1.put("amount",transMoney);
        b1.put("remark","觅东东平台转账");
        request.setBizContent(JSON.toJSONString(b1));
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        if(response.isSuccess()){
            return true;
        }
        return false;
    }

    public AlipayClient getAlipayClient(Integer orderTime) {
        Integer nowTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate("2020-02-13 20:30:00",DateTimeUtils.DATE_PATTERN_TIMESTAMP));
        AlipayClient alipayClient = getAlipayClient();
        if(orderTime < nowTime){
            alipayClient = new DefaultAlipayClient(
                    oldAliPayConfig.getServerUrl(),
                    oldAliPayConfig.getAppid(),
                    oldAliPayConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    oldAliPayConfig.getPublicKey(),
                    "RSA2");
        }
        log.info("支付宝配置：" + JSON.toJSONString(alipayClient));
        return alipayClient;
    }

    public AlipayClient getAlipayClient() {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getServerUrl(),
                alipayConfig.getAppid(),
                alipayConfig.getPrivateKey(),
                "json",
                "UTF-8",
                alipayConfig.getPublicKey(),
                "RSA2");
        return alipayClient;
    }

    public AlipayClient getMddDataBankAlipayClient() {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getServerUrl(),
                alipayConfig.getAppid(),
                alipayConfig.getPrivateKey(),
                "json",
                "UTF-8",
                alipayConfig.getPublicKey(),
                "RSA2");
        return alipayClient;
    }

    @Override
    public AlipayClient getAliMiniAppClient() {
        if(aliMiniAppClient == null) {
            aliMiniAppClient = new DefaultAlipayClient(
                    aliMiniAppConfig.getServerUrl(),
                    aliMiniAppConfig.getAppid(),
                    aliMiniAppConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    aliMiniAppConfig.getPublicKey(),
                    "RSA2");
        }
        return aliMiniAppClient;
    }

    @Override
    public void payByMiniApp(int i) {
        AlipayClient alipayClient  = getAlipayClient();
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.create.
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
        AlipayTradePayModel alipayTradePayModel = new AlipayTradePayModel();
        alipayTradePayModel.setOutTradeNo("123");
        alipayTradePayModel.setTotalAmount("130");
        alipayTradePayModel.setSubject("a");
        alipayTradePayModel.setBuyerId("aaaa");
        request.setBizModel(alipayTradePayModel);
       /* request.setBizContent("{" +
                "\"out_trade_no\":\"20171115010101001\"," +
                "\"total_amount\":0.01," +
                "\"subject\":\"Iphone616G\"," +
                "\"buyer_id\":\"用户pid\"" +
                "}");*/
        try {
            //使用的是execute
            AlipayTradeCreateResponse response = alipayClient.execute(request);
            String trade_no = response.getTradeNo();//获取返回的tradeNO。
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
    }

    @Override
    public Map<String, Object> authMiniAppUser(AlipaySystemOauthTokenResponse userResponse) {
        //String userId = userResponse.getUserId();
        /*BmsUser bmsUser = bmsUserService.findUserByAliUserId(userId);
        if(bmsUser == null) {
            Map<String, Object> registerMap = bmsUserService.creatNewUserByAliUserId(userId, "", Constants.COMMON_FLAG_TRUE, Constants.GENERAL_USER_ROLE_ID);
            if (!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))) {
                return registerMap;
            }
            bmsUser = (BmsUser) registerMap.get("bmsUser");
            bmsUser.setAliUserId(userId);
            bmsUser.setCreateWay(Constants.SMALL_ALI_CLIENT);
        }
        TokenManager.setUser(bmsUser);*/
        AuthMiniAppUserVo authMiniAppUserVo = new AuthMiniAppUserVo();
        authMiniAppUserVo.setAliUserId(userResponse.getUserId());
        /*if(StringUtils.isNotBlank(bmsUser.getPhone())){
            authMiniAppUserVo.setIsBindPhone(Constants.COMMON_FLAG_TRUE_INT);
            authMiniAppUserVo.setToken(TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(Constants.GENERAL_USER_ROLE_ID)));
            if(StringUtils.isNotBlank(bmsUser.getAliNickName())){
                authMiniAppUserVo.setLoginName(bmsUser.getAliNickName());
            }
            if(StringUtils.isNotBlank(bmsUser.getAliAvatar())){
                authMiniAppUserVo.setHeadImgUrl(bmsUser.getAliAvatar());
            }
        }*/
        return ResultMapHelper.success(authMiniAppUserVo,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> saveUserMes(ParamsMap paramsMap) {
        String avatar = paramsMap.getString("avatar");
        String nickName = paramsMap.getString("nickName");
        String gender = paramsMap.getString("gender");
        String province = paramsMap.getString("province");
        String city = paramsMap.getString("city");
        Integer userId = paramsMap.getInteger("userId");
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser == null) {
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,ResultMsg.CODE_USER_NO_EXIST);
        }
        bmsUser.setAliAvatar(avatar);
        bmsUser.setAliCity(city);
        if(StringUtils.isNotBlank(gender)) {
            bmsUser.setAliGender(gender == "M" ? Constants.COMMON_FLAG_TRUE_INT : Constants.COMMON_FLAG_FALSE_INT);
        }
        bmsUser.setAliNickName(nickName);
        bmsUser.setAliProvince(province);
        TokenManager.setUser(bmsUser);
        return ResultMapHelper.success(new HashMap<>(),ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<String, Object> miniAppPhone(String aliUserId,String paramStr) {
        String data = decryptPhoneData(paramStr);
        if(data == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"授权失败，请重试");
        }
        log.info("密文数据：" + data);
        Map<String,Object> finallyData = JSON.parseObject(data);
        if(finallyData.containsKey("code") && "10000".equals(finallyData.get("code").toString())){
            String phone = finallyData.get("mobile").toString();
            BmsUser phoneUser = bmsUserService.findByPhone(phone);
            if(phoneUser == null) {
                Map<String, Object> registerMap = bmsUserService.creatNewUser(phone, "", Constants.COMMON_FLAG_TRUE, Constants.GENERAL_USER_ROLE_ID);
                if (!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))) {
                    return registerMap;
                }
                phoneUser = (BmsUser) registerMap.get("bmsUser");
                phoneUser.setCreateWay(Constants.SMALL_ALI_CLIENT);
            }
            phoneUser.setAliUserId(aliUserId);
            TokenManager.setUser(phoneUser);
            AuthMiniAppUserVo authMiniAppUserVo = new AuthMiniAppUserVo();
            authMiniAppUserVo.setIsBindPhone(Constants.COMMON_FLAG_TRUE_INT);
            authMiniAppUserVo.setUserid(phoneUser.getId());
            authMiniAppUserVo.setHeadImgUrl(phoneUser.getAliAvatar());
            authMiniAppUserVo.setLoginName(phoneUser.getAliNickName());
            authMiniAppUserVo.setPhone(phoneUser.getPhone());
            authMiniAppUserVo.setToken(TokenUtils.getToken(phoneUser.getId().toString(),String.valueOf(Constants.GENERAL_USER_ROLE_ID)));

            return ResultMapHelper.success(authMiniAppUserVo,ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"授权失败，请重试");
    }


    @Override
    public void appPayServicePayNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("----------------阿里服务器消费手机回调-------" + request);
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        log.info("回调数据：" + JSON.toJSONString(params));
        try {
            // 调用SDK验证签名
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayConfig.getPublicKey(),"UTF-8", "RSA2");
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            String info = "flag==" + flag + ";out_trade_no = " + out_trade_no + ";trade_no" + trade_no
                    + ";trade_status = " + trade_status + ";total_amount=" + total_amount;
            log.info("回调价值参数：" + info);
            if (flag && trade_status.equals("TRADE_SUCCESS")) {
                //TODO 进行回调转发
                if(RedisTemplateUtils.getRedisTemplate().hasKey(Constants.REDIS_KEY_MICOS_PAY + out_trade_no)){
                    String notifyUrl = RedisTemplateUtils.getRedisTemplate().opsForValue().get(Constants.REDIS_KEY_MICOS_PAY + out_trade_no).toString();
                    if(StringUtils.isNotBlank(notifyUrl)){
                        if(ApplicationContextHolder.getActiveProfile().equals("preo")){
                            //先转到外部
                            String externalURL = "http://dg.syni.com/MDD_API/commonTool/common/forwardingInterface";
                            params.put("notifyUrl",notifyUrl);
                            RestTemplateUtils.forwardPost(externalURL,request,params);
                        }else {
                            RestTemplateUtils.forwardPost(notifyUrl,request,params);
                        }

                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("阿里App支付回调错误：",e);
        }
    }

    public String decryptPhoneData(String response){
        //1. 获取验签和解密所需要的参数
        Map<String, String> openapiResult = JSON.parseObject(response,
                new TypeReference<Map<String, String>>() {
                }, Feature.OrderedField);
        String signType = "RSA2";
        String charset = "UTF-8";
        String encryptType = "AES";
        String sign = openapiResult.get("sign");
        String content = openapiResult.get("response");

        //如果密文的
        boolean isDataEncrypted = !content.startsWith("{");
        boolean signCheckPass = false;

        //2. 验签
        String signContent = content;
        String signVeriKey = aliMiniAppConfig.getPublicKey();
        String decryptKey = aliMiniAppConfig.getAesKey();
                ;
        //如果是加密的报文则需要在密文的前后添加双引号
        if (isDataEncrypted) {
            signContent = "\"" + signContent + "\"";
        }
        try {
            signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
        } catch (AlipayApiException e) {
            //验签异常, 日志
        }
        if(!signCheckPass) {
            //验签不通过（异常或者报文被篡改），终止流程（不需要做解密）
            return null;
        }

        //3. 解密
        String plainData = null;
        if (isDataEncrypted) {
            try {
                plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
            } catch (AlipayApiException e) {
                //解密异常, 记录日志
                log.error(e.getMessage(),e);
                return null;
            }
        } else {
            plainData = content;
        }
        return plainData;
    }

    @Override
    public void orderRefundQuery(String orderNo,String requestNo) {
        AlipayClient alipayClient  = getAlipayClient();
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.create.
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
        AlipayTradeFastpayRefundQueryModel alipayTradeFastpayRefundQueryModel = new AlipayTradeFastpayRefundQueryModel();
        alipayTradeFastpayRefundQueryModel.setOutTradeNo(orderNo);
        alipayTradeFastpayRefundQueryModel.setOutRequestNo(requestNo);
        request.setBizModel(alipayTradeFastpayRefundQueryModel);
        try {
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("orderRefundQuery data：" + JSON.toJSONString(response));

            }
        } catch (AlipayApiException e) {
            log.error("aliPay orderRefundQuery error",e);
        }

    }
}
